<template>
  <!-- 商品管理 -->
  <div class="pageWrap">
    <el-form :inline="true" :model="formInline">
      <el-form-item label="名称">
        <el-input placeholder="请输入内容" v-model="formInline.name" class="adipt" clearable></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="formInline.brand" clearable filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in brandArr"
            :key="index"
            :label="item.brand"
            :value="item.brand"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品类">
        <el-select v-model="formInline.type" clearable filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in typeArr"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="栏目">
        <el-select v-model="formInline.cate" clearable filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in cateArr"
            :key="index"
            :label="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" @click="getGoods()">查询</el-button>
        <el-button type="primary" @click="addGoods()">添加</el-button>
        <el-button type="primary" @click="exportExcel()">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="goodsData.slice((cur-1)*pSize,cur*pSize)" style="width: 100%">
      <el-table-column label="商品编号" prop="uid" width="150" align="center"></el-table-column>
      <el-table-column label="商品图片" align="center">
        <template slot-scope="{row}">
          <img :src="row.imgUrl" class="pic" v-if="row.ivT=='I'" />
          <video autoplay loop muted :src="row.imgUrl" class="pic" v-else></video>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" width="250" align="center">
        <template slot-scope="{row}">
          <el-input v-model="row.name" placeholder="请输入名称" v-if="row.edit"></el-input>
          <span v-else>{{row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售价" width="120" align="center">
        <template slot-scope="{row}">
          <el-input v-model="row.actPrice" placeholder="销售价" v-if="row.edit"></el-input>
          <span v-else>{{row.actPrice?row.actPrice:'暂无'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="天猫价" width="120" align="center">
        <template slot-scope="{row}">
          <el-input v-model="row.tmPrice" placeholder="天猫价" v-if="row.edit"></el-input>
          <span v-else>{{row.tmPrice&&row.tmPrice>0?row.tmPrice:'暂无'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="原价" width="120" align="center">
        <template slot-scope="{row}">
          <el-input v-model="row.price" placeholder="原价" v-if="row.edit"></el-input>
          <span v-else>{{row.price?row.price:'暂无'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row,$index}">
          <el-button type="text" @click="editGoods(row)">编辑</el-button>
          <el-button type="text" @click="delGoods(row.id,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :hide-on-single-page="goodsData.length<pSize"
      :current-page.sync="cur"
      :page-size="pSize"
      layout="prev, pager, next, jumper"
      :total="goodsData.length"
      class="pagination"
    ></el-pagination>
    <el-dialog
      title="商品信息"
      width="80%"
      :close-on-click-modal="false"
      :visible.sync="showAlert"
      :destroy-on-close="true"
      :center="true"
    >
      <el-form
        ref="goodsForm"
        :model="goodsForm"
        label-width="auto"
        :rules="rules"
        class="alertCon"
      >
        <el-form-item label="商品图片" class="pb long" prop="imgUrl">
          <el-upload
            class="uploader"
            :action="upLoadUrl"
            :show-file-list="false"
            :on-success="(value)=> picSuccess(value)"
            :before-upload="(file)=> beforeUpload(file)"
            name="img"
          >
            <img v-if="goodsForm.imgUrl" :src="goodsForm.imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品名称" prop="name" class="long">
          <el-input v-model="goodsForm.name"></el-input>
        </el-form-item>
        <el-form-item label="销售价" class="ff" prop="actPrice">
          <el-input v-model.number="goodsForm.actPrice"></el-input>
        </el-form-item>
        <el-form-item label="天猫价" class="ff">
          <el-input v-model="goodsForm.tmPrice"></el-input>
        </el-form-item>
        <el-form-item label="原价" class="ff" prop="price">
          <el-input v-model.number="goodsForm.price"></el-input>
        </el-form-item>
        <el-form-item label="品牌" class="ff2">
          <el-select
            v-model="goodsForm.brand"
            filterable
            allow-create
            default-first-option
            placeholder="请选择品牌"
            clearable
          >
            <el-option
              v-for="(item,index) in brandArr"
              :key="index"
              :label="item.brand"
              :value="item.brand"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品类" class="ff2">
          <el-select v-model="goodsForm.type" filterable clearable placeholder="请选择品类">
            <el-option
              v-for="(item,index) in typeArr"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="栏目类别" class="long">
          <el-select
            v-model="goodsForm.cate"
            multiple
            filterable
            clearable
            allow-create
            default-first-option
            placeholder="请选择栏目"
            style="width:100%;"
          >
            <el-option
              v-for="(item,index) in cateArr"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="赛微商城链接" prop="links">
          <el-input v-model="goodsForm.links"></el-input>
        </el-form-item>
        <el-form-item class="long">
          <el-button type="primary" @click="saveGoods('goodsForm')">保存</el-button>
          <!-- <el-button @click="cancle()">取消</el-button> -->
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
import table2excel from "js-table2excel";
export default {
  data() {
    return {
      brandArr: [], //品牌
      typeArr: [], // 品类
      cateArr: [], //栏目
      formInline: {
        name: "",
        brand: "",
        type: "",
        // cate: "",
      },
      goodsData: [],
      cur: 1,
      pSize: 10,
      showAlert: false,
      goodsForm: {
        imgUrl: "",
        name: "",
        actPrice: "",
        tmPrice: "",
        price: "",
        links: "",
        type: "", //品类
        brand: "", //品牌
        cate: "", //栏目
        id: "",
      },
      rules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],

        imgUrl: { required: true, message: "请上传商品图片", trigger: "blur" },
        actPrice: [
          { required: true, message: "请输入活动价", trigger: "blur" },
          { type: "number", message: "必须为数字值" },
        ],
        price: [
          { required: true, message: "请输入原价", trigger: "blur" },
          { type: "number", message: "必须为数字值" },
        ],
        links: { required: true, message: "请输入商品链接", trigger: "blur" },
      },
      upLoadUrl: this.$url + "/sbr/match/uploadImg",
    };
  },
  methods: {
    // 获取品牌
    getBrand() {
      this.$axios.get("/sbr/shop/getShopBrand").then((res) => {
        let rr = res.data.data;
        this.brandArr = rr;
      });
    },
    // 获取品类
    getType() {
      this.$axios.get("/sbr/shop/getShopType").then((res) => {
        let rr = res.data.data;
        this.typeArr = rr;
      });
    },
    // 获取栏目
    getCate() {
      this.$axios.get("/sbr/shop/getShopCate").then((res) => {
        let rr = res.data.data;
        this.cateArr = rr;
      });
    },
    // 导出
    exportExcel() {
      /** column数据的说明 */
      //1.title为column的标题
      //2.key为column对应的key
      //3.type默认是text，若为图片格式type为image , 并且可以设置图片的宽高
      const column = [
        {
          title: "商品编号",
          key: "uid",
          type: "text",
        },
        {
          title: "商品图片",
          key: "imgUrl",
          type: "image",
          width: 80,
          height: 80,
        },
        {
          title: "商品名称",
          key: "name",
          type: "text",
        },
        {
          title: "销售价",
          key: "actPrice",
          type: "text",
        },
        {
          title: "天猫价",
          key: "actPrice",
          type: "text",
        },
        {
          title: "原价",
          key: "actPrice",
          type: "text",
        },
        {
          title: "品牌",
          key: "brand",
          type: "text",
        },
        {
          title: "品类",
          key: "type",
          type: "text",
        },
        {
          title: "栏目",
          key: "cate",
          type: "text",
        },
        {
          title: "商品链接",
          key: "links",
          type: "text",
        },
      ];
      this.goodsData.forEach((v) => {
        if (!v.tmPrice) v.tmPrice = "暂无";
        if (!v.brand) v.brand = "暂无";
        if (!v.type) v.type = "暂无";
        if (!v.cate) v.cate = "暂无";
      });
      //this.newsList是从后端接口中获取数组列表
      //第三个参数是表格名
      table2excel(column, this.goodsData, "商品列表.xls");
    },
    // 获取商品
    getGoods() {
      this.$axios
        .get("/sbr/shop/getShopKu", { params: this.formInline })
        .then((res) => {
          let rr = res.data.data;
          rr.forEach((v) => {
            v.actPrice = Number(v.actPrice);
            v.tmPrice = v.tmPrice != "0" ? v.tmPrice : "";
            v.type = v.type ? Number(v.type) : "";
            v.price = Number(v.price);
            v.edit = false;
            if (v.cate) {
              v.cate = JSON.parse(v.cate);
            }
            let iv = v.imgUrl.split(".");
            let ivT = iv[iv.length - 1];
            if (ivT == "png" || ivT == "jpg") v.ivT = "I";
            else v.ivT = "V";
          });
          this.goodsData = rr;
        });
    },
    // 图片上传成功
    picSuccess(v) {
      this.goodsForm.imgUrl = v.data.filePath;
    },
    // 上传图片
    beforeUpload(file) {
      if (this.goodsForm.imgUrl) {
        let pp = this.goodsForm.imgUrl.split("/");
        pp = this.$Base64.encode(pp[pp.length - 1]);
        this.$axios.get("/sbr/match/delImg?fileName=" + pp);
      }
      const isJPG = file.type === "image/jpeg";
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传图片大小不能超过 1MB!");
      }
      return isJPG && isLt1M;
    },
    addGoods() {
      this.goodsForm = {
        imgUrl: "",
        name: "",
        actPrice: "",
        tmPrice: "",
        price: "",
        links: "",
        type: "", //品类
        brand: "", //品牌
        cate: "", //栏目
        id: "",
      };
      this.showAlert = true;
    },
    // 添加保存  修改保存
    saveGoods(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.goodsForm.actPrice = Number(this.goodsForm.actPrice);
          this.goodsForm.tmPrice = Number(this.goodsForm.tmPrice);
          this.goodsForm.price = Number(this.goodsForm.price);
          this.goodsForm.type = Number(this.goodsForm.type);
          console.log(this.goodsForm);
          if (this.goodsForm.id) {
            this.$axios
              .post("/sbr/shop/updShopKu", this.goodsForm)
              .then((res) => {
                this.$message.success("修改成功");
                this.goodsForm.tmPrice =
                  this.goodsForm.tmPrice == 0 ? "" : this.goodsForm.tmPrice;
                let iv = this.goodsForm.imgUrl.split(".");
                let ivT = iv[iv.length - 1];
                if (ivT == "png" || ivT == "jpg") this.goodsForm.ivT = "I";
                else this.goodsForm.ivT = "V";
                let ind = this.goodsData.findIndex((vv) => {
                  return vv.id == this.goodsForm.id;
                });
                this.goodsData[ind] = this.goodsForm;
                this.$forceUpdate();
                this.showAlert = false;
                // this.getArr();
              });
          } else {
            this.$axios
              .post("/sbr/shop/addShopKu", this.goodsForm)
              .then((res) => {
                this.$message.success("添加成功");
                this.goodsForm.tmPrice =
                  this.goodsForm.tmPrice == 0 ? "" : this.goodsForm.tmPrice;
                let rr = res.data.data;
                this.goodsForm.id = rr.id;
                this.goodsForm.uid = rr.uid;
                let iv = this.goodsForm.imgUrl.split(".");
                let ivT = iv[iv.length - 1];
                if (ivT == "png" || ivT == "jpg") this.goodsForm.ivT = "I";
                else this.goodsForm.ivT = "V";
                this.goodsData.push(this.goodsForm);
                this.$forceUpdate();
                this.showAlert = false;
                // this.getArr();
              });
          }
        } else {
          this.$message.error("请填写完整信息");
          return false;
        }
      });
    },
    // 删除商品
    delGoods(vId, i) {
      if (vId) {
        this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$axios
              .get("/sbr/shop/delShop", { params: { id: vId } })
              .then((res) => {
                this.goodsData.splice((this.cur - 1) * this.pSize + i, 1);
                this.$forceUpdate();
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } else {
        this.goodsData.splice((this.cur - 1) * this.pSize + i, 1);
      }
    },
    // 编辑
    editGoods(row) {
      this.goodsForm = JSON.parse(JSON.stringify(row));
      this.showAlert = true;
    },
  },
  created() {
    this.getBrand();
    this.getType();
    this.getCate();
    this.getGoods();
  },
};
/* <style scoped src="../../../assets/css/goods.css"></style> */
</script>
<style scoped>
.pageWrap {
  margin: 14px;
}
.pic {
  width: 100px;
}
.pagination {
  margin: 5px auto;
}
.alertCon .el-form-item.ff {
  display: inline-block;
  width: 33.33%;
}
.alertCon .el-form-item.ff2 {
  display: inline-block;
  width: 50%;
}
.alertCon .long {
  width: 100%;
}
.uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.uploader >>> .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 125px;
  line-height: 125px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 125px;
  display: block;
}
</style>